﻿using mozhi.smarterp.BasicData.Enums;
using mozhi.smarterp.BasicData.PaymentTerms.Repositories;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace mozhi.smarterp.BasicData.PaymentTerms.Services
{
    public class PaymentTermManager : DomainService
    {
        public IPaymentTermRepository _repository;

        public IGuidGenerator _guidGenerator;

        public PaymentTermManager(IPaymentTermRepository repository, IGuidGenerator guidGenerator)
        {
            _repository = repository;
            _guidGenerator = guidGenerator;
        }

        public async Task<PaymentTerm> GetAsync(Guid? id , string code , string name , bool activate , PaymentTermBasisType basisType , int days , PaymentTermType type)
        {
            var matchCount = await _repository.GetCountAsync(null, code, null, null, id , type) + await _repository.GetCountAsync(null, null, name, null, id , type);

            var typeName = type == PaymentTermType.Payment ? "付款条件" : "收款条件";

            if (matchCount > 0)
                throw new UserFriendlyException($"{typeName}:{code}-{name}已存在", "100000");

            PaymentTerm paymentTerm;

            if(id.HasValue)
            {
                paymentTerm = await _repository.GetAsync(id.Value);

                if (paymentTerm == null)
                    throw new UserFriendlyException($"{typeName}:{id}不存在", "100000");

                paymentTerm.Change(code, name, activate, basisType, days);
            }else
                paymentTerm = new PaymentTerm(_guidGenerator.Create() , code , name , activate , basisType, days , type);

            return paymentTerm;
        }
    }
}
